﻿using System;
using System.Linq;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FlashPay.Management.Controllers
{
    using FlashPay.Management.Filters;
    using FlashPay.Management.ViewModels.User;
    //自定义命名空间
    using FlashPay.Entity;
    using FlashPay.Util;

    #region 基础控制
    /// <summary>
    /// 基础控制
    /// </summary>
    public class BaseController : Controller
    {
        public readonly UserDataKeepManage<UserDataKeepViewModel> _manage;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="_memoryCacheUtil"></param>
        public BaseController(UserDataKeepManage<UserDataKeepViewModel> manage)
        {
            this._manage = manage;
        }

        /// <summary>
        /// OnActionExecuting
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (_manage == null || _manage.data == null)
            {
                filterContext.Result = new JsonResult(new
                {
                    Success = false,
                    ErrorMessage = "授权失败！请联系管理员！",
                    ErrorCode = "100",
                    Callback = @"FlashPay.UI.NoPrivilege()"
                });
            }
            else if (_manage.data.UserID <= 0 || _manage.data.CompanyID <= 0 || _manage.data.MType <= 0)
            {
                filterContext.Result = new JsonResult(new
                {
                    Success = false,
                    ErrorMessage = "授权失败！",
                    ErrorCode = "100",
                    Callback = @"FlashPay.UI.NoPrivilege()"
                });
            }
        }
    }
    #endregion

    #region 自定义方法拦截器
    /// <summary>
    /// 自定义方法拦截器
    /// </summary>
    /// <remarks>2018-06-01 创建</remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 授权码列表
        /// </summary>
        public AuthCode[] Code { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">权限码</param>
        public AuthorizeFilter(params AuthCode[] code)
        {
            this.Code = code;
        }

        /// <summary>
        /// 拦截未登录的用户
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var IsAjaxRequest = false;

            var headers = context.HttpContext.Request.Headers.ContainsKey("x-requested-with");
            if (headers)
            {
                IsAjaxRequest = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            }

            String token = context.HttpContext.Request.Headers["token"];

            if (string.IsNullOrEmpty(token))
            {
                context.Result = new JsonResult(new
                {
                    Success = false,
                    ErrorCode = "请登录！",
                    Callback = @"FlashPay.UI.LoginBox()",
                    IsLogout = true
                });
            }
            else
            {
                try
                {
                    var userDataKeepViewModel = new MemoryCacheUtil().Get<UserDataKeepViewModel>(EncryptHelper.deCryptDES(token));
                    if (userDataKeepViewModel == null)
                    {
                        context.Result = new JsonResult(new
                        {
                            Success = false,
                            ErrorCode = "100",
                            Callback = @"FlashPay.UI.LoginBox()",
                            IsLogout = true
                        });
                    }
                    else
                    {
                        var isAuthority = Code.Any(item => userDataKeepViewModel.UserPermission.Contains(item.ToString()));
                        if (!isAuthority)
                        {
                            context.Result = new JsonResult(new
                            {
                                Success = false,
                                ErrorCode = "100",
                                Callback = @"FlashPay.UI.NoPrivilege()"
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Result = new JsonResult(new
                    {
                        Success = false,
                        ErrorCode = "没有该权限",
                        Callback = @"FlashPay.UI.LoginBox()",
                        IsLogout = true
                    });
                }
            }
        }
    }
    #endregion

}

#region 认证
namespace FlashPay.Management
{
    using FlashPay.Entity;
    //自定义命名空间
    using FlashPay.Util;

    /// <summary>
    /// 认证接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface Authenticate<T>
    {
        T data { set; get; }

        /// <summary>
        /// 获取票据
        /// </summary>
        /// <param name="token"></param>
        void GetTicket(string token);

        /// <summary>
        /// 设置票据
        /// </summary>
        /// <param name="token"></param>
        JResult<string> SetTicket();
    }

    public class AuthenticateImpl<T> : Authenticate<T>
    {
        public T data { set; get; }

        /// <summary>
        /// 获取票据
        /// </summary>
        /// <param name="token"></param>
        public void GetTicket(string token)
        {
            this.data = CacheUtil.Instance.Get<T>(EncryptHelper.deCryptDES(token));
        }

        /// <summary>
        /// 设置票据
        /// </summary>
        /// <param name="token"></param>
        public JResult<string> SetTicket()
        {
            var response = new JResult<string>()
            {
                Success = false
            };

            try
            {
                //生成Token
                var token = Guid.NewGuid().ToString("N");
                //设置缓存
                var status = CacheUtil.Instance.Set(token, data, 120);
                if (status)
                {
                    //验证是否存在
                    var existsStatus = CacheUtil.Instance.Exists(token);
                    if (existsStatus)
                    {
                        response.Success = true;
                        response.Data = EncryptHelper.enCryptDES(token);
                    }
                }

            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
    }

    #region 全局错误
    /// <summary>
    /// 全局错误
    /// </summary>
    public class HttpGlobalExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var response = new JResult()
            {
                Success = false
            };

            //执行过程出现未处理异常
            Exception ex = context.Exception;

            response.ErrorCode = "500";
            response.ErrorMessage = ex.Message;

            context.Result = new JsonResult(response);
            context.HttpContext.Response.StatusCode = 500;
            context.ExceptionHandled = true;

            base.OnException(context);
        }
    }
    #endregion

}
#endregion